package com.xjoyt.pay.master.core.order.handle.callback;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.gateway.params.CallbackParam;
import com.xjoyt.pay.master.core.order.handle.AbstractOrderCallbackHandle;
import com.xjoyt.pay.master.dto.CallbackResult;
import com.xjoyt.pay.master.dto.OrderUrlResult;
import com.xjoyt.pay.master.po.MerchantMoney;
import com.xjoyt.pay.master.po.Order;
import com.xjoyt.pay.master.repository.MerchantMoneyRepository;
import com.xjoyt.pay.master.repository.OrderRepository;
import com.xjoyt.pay.vo.MoneyType;

/**
 * 处理结算
 * 
 * @author Administrator
 *
 */
@Component
public class PayHandle extends AbstractOrderCallbackHandle {

	@Autowired
	private OrderRepository repository;

	@Autowired
	private MerchantMoneyRepository merchantMoneyRepository;

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public ExecuteResult<CallbackResult> handle(CallbackParam param, Order order) throws Exception {
		if (StringUtils.isBlank(order.orderConfig.payUrl)) {
			if (order.pay == null) {
				order.pay = false;
				repository.save(order);
			}
			return getNext().handle(param, order);
		}

		try {
			OrderUrlResult result = restTemplate.postForObject(order.orderConfig.payUrl, order, OrderUrlResult.class);
			if (result != null && result.success) {
				order.pay = true;
				order.payDate = new Date();
			} else {
				order.pay = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("自动结算出错：", e.toString());
			order.pay = false;
		}
		pay(order);
		repository.save(order);
		return getNext().handle(param, order);
	}

	private void pay(Order order) {
		double rate = order.rate == null ? 0D : order.rate;
		long limit = order.limit == null ? 0L : order.limit;
		long minimum = order.minimum == null ? 0L : order.minimum;
		long poundage = order.poundage == null ? 0L : order.poundage;
		long money = order.money == null ? 0L : order.money;
		long payPoundage = (long) (rate * money) + limit + minimum + poundage;
		long cashMoney = money - payPoundage;
		payAdd(order, money);
		payAdd(order, payPoundage);
		if (order.pay == false) {
			return;
		}
		payAdd(order, cashMoney);
	}

	private void payAdd(Order order, long money) {
		// 付款
		MerchantMoney po = new MerchantMoney();
		po.merchant = order.merchant;
		po.no = order.no;
		po.channel = order.orderConfig.channel;
		po.type = MoneyType.PAY;
		if (money >= 0) {
			po.money = +money;
		} else {
			po.money = -money;
		}
		po.addedDate = new Date();
		merchantMoneyRepository.save(po);
	}
}
